from pymongo import MongoClient
import json
from bson import ObjectId
import datetime

# 创建一个可序列化ObjectId和datetime的类
class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        return json.JSONEncoder.default(self, o)

# 创建MongoDB客户端
client = MongoClient('mongodb://localhost:27017/medical_system')
db = client.medical_system

# 查询角色信息
print("角色详情:")
role = db.roles.find_one({'name': 'admin'})
if role:
    print(json.dumps(role, cls=JSONEncoder, indent=2, ensure_ascii=False))
    print("\n角色权限:")
    permissions = role.get('permissions', [])
    print(json.dumps(permissions, indent=2, ensure_ascii=False))
else:
    print("未找到admin角色")

# 查询用户信息
print("\n用户详情:")
user = db.users.find_one({'username': 'admin'})
if user:
    # 移除密码后打印
    user_info = {k: v for k, v in user.items() if k != 'password'}
    print(json.dumps(user_info, cls=JSONEncoder, indent=2, ensure_ascii=False))
    print(f"用户名: {user.get('username')}, 角色: {user.get('role')}")
else:
    print("未找到admin用户")

# 检查用户权限验证
if user and role:
    # 检查用户的角色列表
    role_name = user.get('role')
    role_permissions = role.get('permissions', [])
    
    print("\n权限检查:")
    for perm in ['user:read', 'user:create', 'user:update', 'user:delete']:
        has_perm = perm in role_permissions
        print(f"权限 {perm}: {'有' if has_perm else '无'}")
else:
    print("无法检查权限，用户或角色数据不完整")

# 关闭连接
client.close() 